package com.leo.ktvplayer.util;

import java.security.MessageDigest;

/**
 * .
 */
public class Md5Util {
    public static byte[] encrypt(String source) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            return digest.digest(source.getBytes("UTF-8"));
        } catch(Exception e){
            return null;
        }
    }

    public static String encryptToHex(String source) {
        return toHex(encrypt(source));
    }

    private static final char[] digits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    /**
     * 将字节数值转换成16进制字符串。
     * @param source
     * @return
     */
    public static String toHex(byte[] source) {
        StringBuilder builder = new StringBuilder();
        for(int n : source) {
            if(n < 0)
                n += 256;
            builder.append(digits[n / 16]);
            builder.append(digits[n % 16]);
        }
        return builder.toString();
    }
}
